package br.com.android.financas.activities;

import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.Date;

import org.joda.time.DateTime;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import br.com.android.financas.R;
import br.com.android.financas.repositorio.RepositorioDespesa;
import br.com.android.financas.repositorio.RepositorioPoupanca;
import br.com.android.financas.repositorio.impl.RepositorioDespesaImpl;
import br.com.android.financas.repositorio.impl.RepositorioPoupancaImpl;

public class Widget extends AppWidgetProvider {

	private Context context;
	private RepositorioDespesa repositorioDespesa;
	private RepositorioPoupanca repositorioPoupanca;


	public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
		final int N = appWidgetIds.length;

		this.context = context;

		for (int i = 0; i < N; i++) {
			int appWidgetId = appWidgetIds[i];
			Intent intent = new Intent(context, HomeDespesa.class);
			PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);

			RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
			views.setOnClickPendingIntent(R.widget.abrir, pendingIntent);

			views.setTextViewText(R.widget.total, NumberFormat.getCurrencyInstance().format(getTotal()));
			views.setTextViewText(R.widget.mes, new DateTime().toString("MMMM").toUpperCase());


			Intent appIntent = new Intent(context, Home.class);
			PendingIntent appPending = PendingIntent.getActivity(context, 0,appIntent, 0);

			views.setOnClickPendingIntent(R.widget.total, appPending);
			views.setOnClickPendingIntent(R.widget.mes, appPending);

			appWidgetManager.updateAppWidget(appWidgetId, views);
		}

	}

	private double getTotal() {
		double total=0;
		try {
			repositorioDespesa = new RepositorioDespesaImpl(context);
			repositorioPoupanca = new RepositorioPoupancaImpl(context);

			total= repositorioDespesa.getTotal(new Date());
			total+=repositorioPoupanca.getTotalDespesa(new Date());
		} catch (SQLException e) {}

		return total;
	}


}